package db

import (
	"data_service/models"
	"fmt"
	"gopkg.in/yaml.v2"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"io/ioutil"
	"log"
)

func InitDB() *gorm.DB {
	// 读取配置
	cfgPath := "./config.yaml"
	cfg, err := LoadConfig(cfgPath)
	if err != nil {
		log.Fatalf("failed to load config: %v", err)
	}
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		cfg.DB.User, cfg.DB.Password, cfg.DB.Host, cfg.DB.Port, cfg.DB.Name)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("failed to connect database: ", err)
	}

	// 自动迁移数据库表
	if err := db.AutoMigrate(
		&models.User{},
		&models.Post{},
		&models.PostLike{},
		&models.Friend{},
		&models.Room{},
		&models.Message{},
		&models.Notice{},
		&models.InterestCircle{},
		&models.Log{},
		&models.SecretLocation{},
		&models.SkillExchange{},
		&models.TriviaQuestion{},
	); err != nil {
		log.Fatalf("failed to auto migrate: %v", err)
	}

	return db
}

// LoadConfig 从 config.yaml 读取配置
type Config struct {
	DB struct {
		Host     string `yaml:"host"`
		Port     int    `yaml:"port"`
		User     string `yaml:"user"`
		Password string `yaml:"password"`
		Name     string `yaml:"name"`
	} `yaml:"db"`
}

func LoadConfig(path string) (*Config, error) {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	var cfg Config
	if err := yaml.Unmarshal(data, &cfg); err != nil {
		return nil, err
	}
	return &cfg, nil
}
